package com.charging.controller.admin;

import com.charging.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import com.charging.service.UserService;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/user")
public class UserManageController {

    @Resource
    private UserService userService;

    @GetMapping("/list")
    public String list(Model model) {
        List<User> users = userService.selectAll();
        model.addAttribute("users", users);
        return "admin/user/list";
    }

    // 编辑用户表单
    @GetMapping("/edit/{id}")
    public String editUserForm(@PathVariable Long id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "admin/user/edit";
    }

    @PostMapping("/edit")
    public String edit(@ModelAttribute User user) {
        userService.updateUser(user);
        return "admin/user/list";
    }


    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("user", new User());
        return "admin/user/add";
    }

    @PostMapping("/add")
    public String add(User user) {
        if (user.getCreateTime() == null) {
            user.setCreateTime(new Date()); // 或 LocalDateTime.now()
        }
        if (user.getUpdateTime() == null) {
            user.setUpdateTime(new Date()); // 或 LocalDateTime.now()
        }
        userService.addUser(user);
        return "admin/user/list";
    }

    @GetMapping("/detail/{id}")
    public String userDetail(@PathVariable Long id, Model model) {
        model.addAttribute("user", userService.getUserById(id));
        return "admin/user/detail";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id) {
        userService.deleteUser(id);
        return "admin/user/list";
    }
}